import React, { useState } from 'react'
import { 
  Card, 
  Table, 
  Space, 
  Button, 
  Tag, 
  Modal, 
  Form, 
  Input, 
  InputNumber, 
  Select, 
  notification,
  Tabs,
  Row,
  Col,
  Statistic,
  Progress,
} from 'antd'
import { 
  PlayCircleOutlined, 
  PauseCircleOutlined, 
  SettingOutlined,
  DeleteOutlined,
  SyncOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons'
import { useQuery, useMutation, useQueryClient } from 'react-query'
import { shardTaskApi } from '../services/shardTask'

const { Option } = Select
const { TabPane } = Tabs
const { confirm } = Modal

const TaskManagement: React.FC = () => {
  const [activeTab, setActiveTab] = useState('optimization')
  const [triggerModalVisible, setTriggerModalVisible] = useState(false)
  const [selectedJobId, setSelectedJobId] = useState<string>('')
  const [form] = Form.useForm()
  const queryClient = useQueryClient()

  // 获取分片策略
  const { data: strategies, isLoading: strategiesLoading } = useQuery(
    'shardingStrategies',
    shardTaskApi.getShardingStrategies
  )

  // 获取分片处理器
  const { data: handlers, isLoading: handlersLoading } = useQuery(
    'shardHandlers',
    shardTaskApi.getShardHandlers
  )

  // 获取集群节点
  const { data: clusterNodes, isLoading: nodesLoading } = useQuery(
    'clusterNodes',
    shardTaskApi.getClusterNodes,
    { refetchInterval: 10000 }
  )

  // 分片优化mutation
  const optimizationMutation = useMutation(shardTaskApi.getShardOptimization, {
    onSuccess: (data) => {
      notification.success({
        message: '分片优化建议生成成功',
        description: `推荐分片数: ${data.recommended_shards}，预计执行时间: ${data.estimated_total_time.toFixed(2)}秒`,
        duration: 5,
      })
    },
    onError: (error: any) => {
      notification.error({
        message: '优化计算失败',
        description: error.detail || '未知错误',
        duration: 5,
      })
    },
  })

  // 清理分片锁mutation
  const cleanupMutation = useMutation(shardTaskApi.cleanupCompletedShards, {
    onSuccess: (data) => {
      notification.success({
        message: '清理完成',
        description: `已清理 ${data.cleaned_count} 个过期分片锁`,
        duration: 5,
      })
      queryClient.invalidateQueries('clusterNodes')
    },
    onError: (error: any) => {
      notification.error({
        message: '清理失败',
        description: error.detail || '未知错误',
        duration: 5,
      })
    },
  })

  // 触发分片执行mutation
  const triggerMutation = useMutation(
    ({ jobId, data }: { jobId: string; data: any }) => 
      shardTaskApi.triggerShardExecution(jobId, data),
    {
      onSuccess: (data) => {
        notification.success({
          message: '分片任务触发成功',
          description: data.message,
          duration: 5,
        })
        setTriggerModalVisible(false)
        form.resetFields()
        queryClient.invalidateQueries('executionStatus')
      },
      onError: (error: any) => {
        notification.error({
          message: '触发失败',
          description: error.detail || '未知错误',
          duration: 5,
        })
      },
    }
  )

  // 执行分片优化
  const handleOptimization = async (values: any) => {
    await optimizationMutation.mutateAsync(values)
  }

  // 清理分片锁
  const handleCleanup = (jobId?: string) => {
    confirm({
      title: '确认清理',
      icon: <ExclamationCircleOutlined />,
      content: jobId ? `确认清理任务 ${jobId} 的分片锁？` : '确认清理所有过期的分片锁？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => cleanupMutation.mutate(jobId),
    })
  }

  // 触发分片任务
  const handleTriggerTask = async (values: any) => {
    await triggerMutation.mutateAsync({
      jobId: selectedJobId,
      data: values,
    })
  }

  // 执行记录表格列定义
  const executionColumns = [
    {
      title: '任务ID',
      dataIndex: 'job_id',
      key: 'job_id',
      render: (text: string) => (
        <span style={{ fontFamily: 'monospace', fontSize: 12 }}>
          {text.substring(0, 8)}...
        </span>
      ),
    },
    {
      title: '处理器',
      dataIndex: 'handler_name',
      key: 'handler_name',
      render: (text: string) => {
        const displayName = text.replace('demo_', '').replace(/_/g, ' ')
        return <Tag color="blue">{displayName}</Tag>
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        const statusConfig = {
          SUCCESS: { color: 'green', text: '成功' },
          FAILED: { color: 'red', text: '失败' },
          RUNNING: { color: 'blue', text: '运行中' },
          PENDING: { color: 'orange', text: '等待中' },
        }
        const config = statusConfig[status as keyof typeof statusConfig] || { color: 'default', text: status }
        return <Tag color={config.color}>{config.text}</Tag>
      },
    },
    {
      title: '分片信息',
      dataIndex: 'shard_param',
      key: 'shard_param',
      render: (param: string) => param || '-',
    },
    {
      title: '开始时间',
      dataIndex: 'start_time',
      key: 'start_time',
      render: (time: string) => time ? new Date(time).toLocaleString() : '-',
    },
    {
      title: '操作',
      key: 'action',
      render: (record: any) => (
        <Space size="small">
          <Button 
            size="small" 
            icon={<PlayCircleOutlined />}
            onClick={() => {
              setSelectedJobId(record.job_id)
              setTriggerModalVisible(true)
            }}
          >
            重新执行
          </Button>
          <Button 
            size="small" 
            icon={<DeleteOutlined />}
            danger
            onClick={() => handleCleanup(record.job_id)}
          >
            清理锁
          </Button>
        </Space>
      ),
    },
  ]

  // 集群节点表格列定义
  const nodeColumns = [
    {
      title: '节点ID',
      dataIndex: 'node_id',
      key: 'node_id',
      render: (text: string) => <Tag color="purple">{text}</Tag>,
    },
    {
      title: '活跃分片',
      dataIndex: 'active_shards',
      key: 'active_shards',
      render: (count: number) => (
        <span>
          <span className="status-indicator status-processing"></span>
          {count} 个
        </span>
      ),
    },
    {
      title: '负载率',
      key: 'load_rate',
      render: (record: any) => {
        const loadRate = clusterNodes ? (record.active_shards / clusterNodes.total_active_shards * 100) : 0
        return (
          <Progress 
            percent={loadRate} 
            size="small" 
            showInfo={false}
            strokeColor={{
              '0%': '#108ee9',
              '100%': '#87d068',
            }}
          />
        )
      },
    },
    {
      title: '最后活跃',
      dataIndex: 'last_expire_time',
      key: 'last_expire_time',
      render: (time: string) => time ? new Date(time).toLocaleString() : '-',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={status === 'active' ? 'green' : 'red'}>
          {status === 'active' ? '在线' : '离线'}
        </Tag>
      ),
    },
  ]

  return (
    <div>
      <div style={{ marginBottom: 24 }}>
        <h1 style={{ fontSize: 24, fontWeight: 'bold', marginBottom: 8 }}>
          <SettingOutlined style={{ marginRight: 8, color: '#1890ff' }} />
          分片任务管理
        </h1>
        <p style={{ color: '#666', fontSize: 14 }}>
          管理和监控分片集群任务的执行状态，优化分片配置，清理过期资源
        </p>
      </div>

      <Tabs activeKey={activeTab} onChange={setActiveTab}>
        <TabPane tab="分片优化" key="optimization">
          <Row gutter={[16, 16]}>
            <Col xs={24} lg={12}>
              <Card title="分片优化计算">
                <Form
                  layout="vertical"
                  onFinish={handleOptimization}
                  initialValues={{
                    data_size: 10000,
                    available_nodes: 3,
                    processing_time_per_item: 0.1,
                  }}
                >
                  <Form.Item
                    name="data_size"
                    label="数据总量"
                    rules={[{ required: true, message: '请输入数据总量' }]}
                  >
                    <InputNumber
                      min={1}
                      max={1000000}
                      style={{ width: '100%' }}
                      placeholder="要处理的数据总量"
                    />
                  </Form.Item>
                  
                  <Form.Item
                    name="available_nodes"
                    label="可用节点数"
                    rules={[{ required: true, message: '请输入可用节点数' }]}
                  >
                    <InputNumber
                      min={1}
                      max={20}
                      style={{ width: '100%' }}
                      placeholder="集群中可用的节点数量"
                    />
                  </Form.Item>
                  
                  <Form.Item
                    name="processing_time_per_item"
                    label="单项处理时间(秒)"
                    rules={[{ required: true, message: '请输入单项处理时间' }]}
                  >
                    <InputNumber
                      min={0.001}
                      max={10}
                      step={0.01}
                      style={{ width: '100%' }}
                      placeholder="处理每个数据项的时间"
                    />
                  </Form.Item>
                  
                  <Form.Item>
                    <Button 
                      type="primary" 
                      htmlType="submit" 
                      loading={optimizationMutation.isLoading}
                      block
                    >
                      计算最优分片
                    </Button>
                  </Form.Item>
                </Form>

                {optimizationMutation.data && (
                  <div style={{ marginTop: 16, padding: 16, background: '#f6ffed', border: '1px solid #b7eb8f', borderRadius: 6 }}>
                    <h4>优化建议结果:</h4>
                    <Row gutter={16}>
                      <Col span={12}>
                        <Statistic
                          title="推荐分片数"
                          value={optimizationMutation.data.recommended_shards}
                          suffix="个"
                        />
                      </Col>
                      <Col span={12}>
                        <Statistic
                          title="预计总时间"
                          value={optimizationMutation.data.estimated_total_time.toFixed(2)}
                          suffix="秒"
                        />
                      </Col>
                      <Col span={12}>
                        <Statistic
                          title="单分片时间"
                          value={optimizationMutation.data.estimated_time_per_shard.toFixed(2)}
                          suffix="秒"
                        />
                      </Col>
                      <Col span={12}>
                        <Statistic
                          title="资源利用率"
                          value={(optimizationMutation.data.utilization_rate * 100).toFixed(1)}
                          suffix="%"
                        />
                      </Col>
                    </Row>
                  </div>
                )}
              </Card>
            </Col>

            <Col xs={24} lg={12}>
              <Card title="分片策略说明" loading={strategiesLoading}>
                <div style={{ maxHeight: 400, overflowY: 'auto' }}>
                  {strategies?.strategies?.map((strategy, index) => (
                    <div key={index} style={{ marginBottom: 16, padding: 12, background: '#f9f9f9', borderRadius: 4 }}>
                      <div style={{ fontWeight: 'bold', marginBottom: 4 }}>
                        <Tag color="blue">{strategy.name}</Tag>
                        {strategy.name === 'hash' && '哈希分片'}
                        {strategy.name === 'range' && '范围分片'}
                        {strategy.name === 'round_robin' && '轮询分片'}
                        {strategy.name === 'custom' && '自定义分片'}
                      </div>
                      <div style={{ fontSize: 12, color: '#666', marginBottom: 4 }}>
                        {strategy.description}
                      </div>
                      <div style={{ fontSize: 12, color: '#999' }}>
                        适用场景: {strategy.use_case}
                      </div>
                    </div>
                  ))}
                </div>
              </Card>
            </Col>
          </Row>
        </TabPane>

        <TabPane tab="集群节点" key="cluster">
          <Card 
            title="集群节点状态" 
            loading={nodesLoading}
            extra={
              <Space>
                <Tag color="green">总节点: {clusterNodes?.total_nodes || 0}</Tag>
                <Tag color="blue">活跃分片: {clusterNodes?.total_active_shards || 0}</Tag>
              </Space>
            }
          >
            <Table
              columns={nodeColumns}
              dataSource={clusterNodes?.nodes || []}
              rowKey="node_id"
              pagination={false}
              scroll={{ x: 800 }}
            />
          </Card>
        </TabPane>
      </Tabs>

      {/* 触发分片任务Modal */}
      <Modal
        title="手动触发分片任务"
        open={triggerModalVisible}
        onCancel={() => setTriggerModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleTriggerTask}
          initialValues={{
            shard_count: 3,
            shard_strategy: 'hash',
            parameters: {},
          }}
        >
          <Form.Item
            name="handler_name"
            label="处理器名称"
            rules={[{ required: true, message: '请选择处理器' }]}
          >
            <Select placeholder="选择要执行的处理器" loading={handlersLoading}>
              {handlers?.handlers?.map((handler) => (
                <Option key={handler.name} value={handler.name}>
                  {handler.description}
                </Option>
              ))}
            </Select>
          </Form.Item>
          
          <Form.Item
            name="shard_count"
            label="分片数量"
            rules={[{ required: true, message: '请输入分片数量' }]}
          >
            <InputNumber min={1} max={20} style={{ width: '100%' }} />
          </Form.Item>
          
          <Form.Item
            name="shard_strategy"
            label="分片策略"
            rules={[{ required: true, message: '请选择分片策略' }]}
          >
            <Select>
              <Option value="hash">哈希分片</Option>
              <Option value="range">范围分片</Option>
              <Option value="round_robin">轮询分片</Option>
              <Option value="custom">自定义分片</Option>
            </Select>
          </Form.Item>
          
          <Form.Item>
            <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
              <Button onClick={() => setTriggerModalVisible(false)}>
                取消
              </Button>
              <Button 
                type="primary" 
                htmlType="submit" 
                loading={triggerMutation.isLoading}
              >
                触发执行
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default TaskManagement